package com.xb.p21_handlerdemo;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    final static String Tag="Handler：";
    final static int TEST_MSG=1;
    TextView txt=null;

    Handler handler=new Handler(){//在handleMessage中处理界面
        public void handleMessage(Message message){
            Log.i(Tag,"当前线程：Handler,id="+Thread.currentThread().getId());
            switch (message.what){
                case TEST_MSG:
                    txt.setText("工作线程：文本内容");
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Log.i(Tag,"当前线程：onCreate,id="+Thread.currentThread().getId());
        txt=findViewById(R.id.hello);

        new ActivityThread().start();
    }

    //多线程
    class ActivityThread extends Thread{
        public void run(){
            try {//模拟处理耗时操作
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            Log.i(Tag,"当前线程：ActivityThread,id="+Thread.currentThread().getId());
            //txt.setText("工作线程：文本内容");
            Message message=new Message();
            message.what=TEST_MSG;
            handler.sendMessage(message);
        }
    }
}